import {actions} from '../common/window/store'
import store from "../store";
import {notification} from 'antd';
import Http from "./http";
import _ from 'lodash';
import {systemUpload} from "@/util/Api";
import {toBase64} from "@/util/CodeUtils";
/**
 * 随机字符
 * @return {string}
 */
export function RandomStr(max = 10) {
    return Math.random().toString().substring(0, parseInt(max))
}

export function writeClip(str) {
    window.navigator.clipboard.writeText(str).then(r => {
        successMsg("复制成功！")
    }).catch(e => {
        errorMsg("哎呀，复制失败了！")
    })
}

export function readClip() {
    return window.navigator.clipboard.readText();
}

/**
 * 富文本编辑器上传文件
 */
export function editorUpload(param) {
    let formData = new FormData();
    formData.append('file', param.file);

    systemUpload(
        formData,
        (event) => {
            // 上传进度发生变化时调用param.progress
            param.progress(event.loaded / event.total * 100)
        }
    ).then(response => {
        param.success({
            url: response.data,
            meta: {
                id: response.data,
                title: response.data,
                alt: response.data,
                loop: false, // 指定音视频是否循环播放
                autoPlay: false, // 指定音视频是否自动播放
                controls: false, // 指定音视频是否显示控制栏
                poster: '', // 指定视频播放器的封面
            }
        })
    });
}

/**
 * 密码强度判断
 * @param string 密码字符串
 * @returns int -1 位数不够 0弱  1 中  2 很强
 */
export function AuthPasswd(string) {
    if (string.length >= 8) {
        if (/[a-zA-Z]+/.test(string) && /[0-9]+/.test(string) && /\W+\D+/.test(string)) {
            return 2;
        } else if (/[a-zA-Z]+/.test(string) || /[0-9]+/.test(string) || /\W+\D+/.test(string)) {
            if (/[a-zA-Z]+/.test(string) && /[0-9]+/.test(string)) {
                return 1;
            } else if (/\[a-zA-Z]+/.test(string) && /\W+\D+/.test(string)) {
                return 1;
            } else if (/[0-9]+/.test(string) && /\W+\D+/.test(string)) {
                return 1;
            } else {
                return 0;
            }
        }
    } else if (string.length >= 1) {
        return -1;
    } else {
        return null;
    }
}

/**
 * 获取url参数
 * eg: http://www.baidu.com/?path=1 获取key 为 "path" 的 value
 * @param variable
 * @returns {string|null}
 */
export function getQueryVariable(variable) {
    if (!window.location.search) {
        return null;
    }
    let query = window.location.search.substring(1);
    let vars = query.split("&");
    if (vars.length === 0) {
        return null;
    }
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] === variable) {
            return pair[1];
        }
    }
    return null;
}

export function buildToFullHtml(html) {
    return "<html style='width: 100%; height: 100%; margin: 0px; padding: 0px;'><head>" +
        "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" />" +
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
        "<title></title></head>" +
        "<body style='width: 100%; height: 100%; margin: 0px; padding: 0px;'>" +
        html +
        "</body></html>";
}

/* 全局Loading */
export function load(boolean) {
    store.dispatch(actions.loadingScreenView(boolean));
}

/* 此方法是用来判断用户是否已经登录 */
export function isLogin() {
    let uid = queryState('user.id');
    return !_.isNull(uid) && parseInt(uid) > 0;
}

export function to(where){
    window._ROUTER_.push(where)
}

/* 不同类型平台对应不同类型素材 */
export const StaticArray = {
    'PS4': {
        color: '#108ee9',
        iconType: 'icon-playstation'
    },
    'Switch': {
        color: '#f50',
        iconType: 'icon-switch-fill'
    },
}

/* 全局成功提示 */
export function successMsg(value) {
    // message.success({
    //     content:value
    // }).then(r => null);
    notification['success']({
        key: JSON.stringify(value),
        top: 20,
        message: <span style={{color: 'green'}}>成功！</span>,
        description: <span style={{color: "#666"}}>{value}</span>,
        duration: 5.5,
        style: {zIndex: '2000', borderRadius: '10px'}
    });
}

/* 全局成功提示 */
export function successTitleMsg(title,value) {
    // message.success({
    //     content:value
    // }).then(r => null);
    notification['success']({
        key: JSON.stringify(value),
        top: 20,
        message: <span style={{color: 'green'}}>{title}</span>,
        description: <span style={{color: "#666"}}>{value}</span>,
        duration: 5.5,
        style: {zIndex: '2000', borderRadius: '10px'}
    });
}

/* 全局失败提示 */
export function errorMsg(value) {
    // message.error(value).then(r => null);
    notification['error']({
        key: JSON.stringify(value),
        top: 20,
        message: <span style={{color: 'red'}}>失败！</span>,
        description: <span style={{color: "#666"}}>{value}</span>,
        duration: 5.5,
        style: {zIndex: '2000', borderRadius: '10px'}
    });
}

/* 全局警告提示 */
export function warnMsg(value) {
    // message.warn(value).then(r => null);
    notification['warn']({
        key: JSON.stringify(value),
        top: 20,
        message: <span style={{color: 'orange'}}>注意！</span>,
        description: <span style={{color: "#666"}}>{value}</span>,
        duration: 5.5,
        style: {zIndex: '2000', borderRadius: '10px'}
    });
}

/* 转换成带小数点 */
export function toThousands(num) {
    var num = (num || 0).toString(), result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) {
        result = num + result;
    }
    return result;
}

export const Api = {
    LoginApi: '/sys/user/info/login',
    SignUpApi: '/sys/user/info/register',
    UserUploadHeaderImage: '/sys/f-info/uploadImage',
    changeStatus: '/admin/user/change-status',
    uploadFiles: '/sys/f-info/upload',
};


export function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

export async function queryAllStatusInfo(statusId) {
    await Http.get(`${Api.queryStatusInfo}`).then(res => {
        if (res.success) {
            localStorage.setItem('status', JSON.stringify(res.data));
        }
    }).catch(e => {
    })
}

export function ScienceNumber(num_str) {
    num_str = num_str.toString();
    if (num_str.indexOf("+") !== -1) {
        num_str = num_str.replace("+", "");
    }
    if (num_str.indexOf("E") !== -1 || num_str.indexOf("e") !== -1) {
        var resValue = "",
            power = "",
            result = null,
            dotIndex = 0,
            resArr = [],
            sym = "";
        var numStr = num_str.toString();
        if (numStr[0] === "-") {
            //如果为负数，转成正数处理，先去掉‘-’号，并保存‘-’.
            numStr = numStr.substr(1);
            sym = "-";
        }
        if (numStr.indexOf("E") !== -1 || numStr.indexOf("e") !== -1) {
            var regExp = new RegExp(
                "^(((\\d+.?\\d+)|(\\d+))[Ee]{1}((-(\\d+))|(\\d+)))$",
                "ig"
            );
            result = regExp.exec(numStr);
            if (result != null) {
                resValue = result[2];
                power = result[5];
                result = null;
            }
            if (!resValue && !power) {
                return false;
            }
            dotIndex = resValue.indexOf(".") === -1 ? 0 : resValue.indexOf(".");
            resValue = resValue.replace(".", "");
            resArr = resValue.split("");
            if (Number(power) >= 0) {
                var subres = resValue.substr(dotIndex);
                power = Number(power);
                //幂数大于小数点后面的数字位数时，后面加0
                for (var i = 0; i <= power - subres.length; i++) {
                    resArr.push("0");
                }
                if (power - subres.length < 0) {
                    resArr.splice(dotIndex + power, 0, ".");
                }
            } else {
                power = power.replace("-", "");
                power = Number(power);
                //幂数大于等于 小数点的index位置, 前面加0
                for (var i = 0; i < power - dotIndex; i++) {
                    resArr.unshift("0");
                }
                var n = power - dotIndex >= 0 ? 1 : -(power - dotIndex);
                resArr.splice(n, 0, ".");
            }
        }
        resValue = resArr.join("");
        return sym + resValue;
    } else {
        toThousands(num_str);
    }
}

/**
 * 全局通过传参来访问state
 * 如想获取user 下的 token 则 → queryState('user.token')  或 queryState('user','token')
 * @returns {string}
 */
export function queryState() {
    let arg = [];
    /* 获取参数列 */
    for (let argument of arguments) {
        /* 只接收字符串作为检索条件 */
        if (!argument instanceof String) {
            throw new Error("错误的参数类型");
        }
        /* 检索条件为空 */
        if (_.isEmpty(argument)) return "";

        /* 拆分参数条件并全部合并到arg数组中 */
        if (argument.indexOf('.') !== -1) {
            arg = arg.concat(argument.split('.'));
        }
    }

    if (arg.length === 0) {
        arg = arguments;
    }

    let result = '';
    let state = store.getState().toJS();
    for (let i = 0; i < arg.length; i++) {
        if (_.isEmpty(result)) {
            result = state[arg[i]];
        } else {
            result = result[arg[i]];
        }
    }
    return result;
}



